package com.runshu.newsmartark.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.naz.serial.port.ModuleManager;
import com.naz.serial.port.SerialPort;
import com.open.hule.library.entity.AppUpdate;
import com.open.hule.library.utils.UpdateManager;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.dbutil.DBUtils;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.ApkVersionEntity;
import com.runshu.newsmartark.entity.HwInfo;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.entity.WeatherEntity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.GetVersionContract;
import com.runshu.newsmartark.mvp.contract.HwHeartContract;
import com.runshu.newsmartark.mvp.contract.MainHomeContract;
import com.runshu.newsmartark.mvp.contract.ReadCardContract;
import com.runshu.newsmartark.mvp.model.GetVersionModel;
import com.runshu.newsmartark.mvp.model.HwHeartModel;
import com.runshu.newsmartark.mvp.model.MainHomeModel;
import com.runshu.newsmartark.mvp.model.ReadCardModel;
import com.runshu.newsmartark.mvp.presenter.GetVersionPresenter;
import com.runshu.newsmartark.mvp.presenter.HwHeartPresenter;
import com.runshu.newsmartark.mvp.presenter.MainHomePresenter;
import com.runshu.newsmartark.mvp.presenter.ReadCardPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.networkstate.annotation.NetworkSubscribe;
import com.runshu.newsmartark.networkstate.type.NetFilterType;
import com.runshu.newsmartark.networkstate.type.NetType;
import com.runshu.newsmartark.reader.base.ReaderBase;
import com.runshu.newsmartark.reader.helper.ReaderHelper;
import com.runshu.newsmartark.reader.helper.ReaderSetting;
import com.runshu.newsmartark.service.SelfCheckService;
import com.runshu.newsmartark.service.SyncDataService;
import com.runshu.newsmartark.util.LodDialogClass;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.NetStatusUtils;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.ToolScanner;
import com.runshu.newsmartark.util.UserCardUtil;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wch.ch34xuartdriver.CH34xUARTDriver;

import static com.runshu.newsmartark.common.ConstantUrl.Share_StockNum;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isAdmin;

@BindEventBus
public class MainActivity extends BaseActivity implements ViewTreeObserver.OnGlobalLayoutListener, MainHomeContract.View, GetVersionContract.View, HwHeartContract.View, ToolScanner.OnScanSuccessListener, ReadCardContract.View {
    private static final String TAG = "MainActivity";
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.img_weather)
    ImageView mImgWeather;
    @BindView(R.id.tv_wendu)
    TextView mTvWendu;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.rela_info)
    RelativeLayout mRelaInfo;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.rela_exit)
    RelativeLayout mRelaExit;
    @BindView(R.id.tv_stock_num)
    TextView mTvStockNum;
    @BindView(R.id.tv_hint_opean)
    TextView mTvHintOpean;
    @BindView(R.id.rela_opean_door)
    RelativeLayout mRelaOpeanDoor;
    @BindView(R.id.tv_hint_manager)
    TextView mTvHintManager;
    @BindView(R.id.rela_manager_door)
    RelativeLayout mRelaManagerDoor;
    @BindView(R.id.img_phone)
    ImageView mImgPhone;
    @BindView(R.id.tv_mac_rigth)
    TextView mTvMacRigth;
    @BindView(R.id.tv_mac_left)
    TextView mTvMacLeft;
    @BindView(R.id.tv_exit)
    TextView mTvExit;
    @BindView(R.id.tv_time)
    TextClock mTvTime;
    @BindView(R.id.tv_search_all)
    TextView mTvSearchAll;
    @BindView(R.id.rela_search_pro)
    RelativeLayout mRelaSearchPro;
    @BindView(R.id.tv_wdu)
    TextView mTvWdu;

    @BindView(R.id.tv_sdu)
    TextView mTvSdu;

    @BindView(R.id.rela_wendu)
    View relaWendu;

    @BindView(R.id.rela_shidu)
    View relaShidu;

    private CommonShowDialog commonShowDialog;
    private final String macAddress = MacUtils.getFormatMacAddr();  //"EA06GC27A573";
    private MainHomePresenter homePresenter;
    private GetVersionPresenter versionPresenter;
    private HwHeartPresenter heartPresenter;
    private CountDownTimer timerDialog;
    private CountDownTimer timerExit;
    public static SerialPort mSerialPort = null;
    private ReaderHelper mReaderHelper;
    private ReaderBase readerBase;
    private static ReaderSetting m_curReaderSetting;
    final static int COUNTS = 5;//点击次数
    final static long DURATION = 3 * 1000;//规定有效时间
    long[] mHits = new long[COUNTS];
    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE

    };
    private static final String ACTION_USB_PERMISSION = "com.leo.wiipu.drinkserialport.USB_PERMISSION";

    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    private ReadCardPresenter readCardPresenter;
    private ToolScanner toolScanner;
    private LocalBroadcastManager lbm;
    IntentFilter itent;
    //温控
    private int retval;
    public boolean isOpen = false;
    private MyHandler wenkHandler;
    public ReadThread readThread;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        Aria.get( this ).getDownloadConfig().setMaxTaskNum( 1 );
        Aria.download(this).register();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        lbm = LocalBroadcastManager.getInstance( this );
        itent = new IntentFilter();
        itent.addAction( ReaderHelper.BROADCAST_WRITE_LOG );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_READER_SETTING );
        toolScanner = new ToolScanner( this );
        readCardPresenter = new ReadCardPresenter( this, new ReadCardModel() );
        heartPresenter = new HwHeartPresenter( this, new HwHeartModel() );
        homePresenter = new MainHomePresenter( this, new MainHomeModel() );
        versionPresenter = new GetVersionPresenter( this, new GetVersionModel() );
        mTvMacRigth.setText( macAddress );
        mTvDate.setText( StringUtils.getYearMonthHourMinuteTimeChinese( Calendar.getInstance().getTimeInMillis() ) + " " + StringUtils.getTodayStringWeek() );
        relaWendu.setVisibility( View.GONE );
        relaShidu.setVisibility( View.GONE );

    }


    @Override
    protected void initData() {
        UsbManager();
        homePresenter.getIndexCount( macAddress );
        boolean isFirst = (boolean) SharedPreferencesUtils.get( MyApplication.getApplication(), ConstantUrl.Share_LoadingFirst, true );
        if (isFirst) {
            LodDialogClass.showCustomCircleProgressDialog( context );
            LodDialogClass.setCustomCircleProgressDialogHintText( "初始化数据中..." );
        }
        try {

            mSerialPort = new SerialPort( new File( ConstantUrl.Share_takeStockPartPort ), 115200, 0 );
            ModuleManager.newInstance().setUHFStatus( true );
            mReaderHelper = ReaderHelper.getDefaultHelper();
            try {
                mReaderHelper.setReader( mSerialPort.getInputStream(), mSerialPort.getOutputStream() );
            } catch (Exception e) {
                e.printStackTrace();
            }
            readerBase = mReaderHelper.getReader();
            m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //测试静默更新
    }


    @Override
    protected void bindListener() {
        mTvTime.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get( Calendar.HOUR_OF_DAY );
                int min = cal.get( Calendar.MINUTE );
                if (min == 0 || min == 30) {
                    LogUtil.e( TAG, "现在是北京时间" + hour + ":" + min );
                    homePresenter.getWeath( macAddress );
                    heartPresenter.sendHwHeart( macAddress );
                    homePresenter.getIndexCount( macAddress );

                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        } );
    }

    @Override
    protected void onResume() {
        super.onResume();
        startService( new Intent( MainActivity.this, SyncDataService.class ) );
        startService( new Intent( MainActivity.this, SelfCheckService.class ) );
        mTvStockNum.setText( (String) SharedPreferencesUtils.get( context, Share_StockNum, "0" ) );
        //同步接口数据（医院信息， 基本信息 ====）
        new Thread( new Runnable() {
            @Override
            public void run() {
                RefreshUtils.getInstance().refreshAll();
            }
        } ).start();

        if (timerExit != null) {
            timerExit.cancel();
        }
        if (hasAuth()) {
            mRelaExit.setVisibility( View.VISIBLE );
            countDownExit();
        } else {
            mRelaExit.setVisibility( View.GONE );
        }
        //清除管理模式
        SharedPreferencesUtils.remove( context, Share_isAdmin );
        heartPresenter.sendHwHeart( macAddress );
        homePresenter.getWeath( macAddress );
//        homePresenter.getIndexCount( macAddress );
        versionPresenter.getVersionInfo( macAddress, String.valueOf( MacUtils.getLocalVersion( context ) ) );
    }


    private void showExitDia() {
        commonShowDialog = new CommonShowDialog( context );
        commonShowDialog.setContent( "已安全退出" );
        commonShowDialog.setContentHint( "欢迎下次使用" );
        commonShowDialog.setImgShow( R.mipmap.icon_dia_exit );
        commonShowDialog.show();
        countDownShowDia();

    }

    @OnClick({R.id.tv_mac_rigth, R.id.rela_search_pro, R.id.rela_exit, R.id.rela_opean_door, R.id.rela_manager_door, R.id.tv_exit})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.rela_opean_door:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                if (hasAuth()) {
                    connect();
                } else {
//                    intent.setClass(context, LoginActivity.class);
//                    startActivity(intent);
                    SoundPoolUtils.play( context, R.raw.raw_face, 0 );
                    intent.setClass( context, RegisterAndRecognizeActivity.class );
                    startActivity( intent );
                }
                break;
            case R.id.rela_manager_door:
                if (hasAuth()) {
                    if (MyApplication.getUserInfoGlob().isAdmin()) {
                        if (timerExit != null) {
                            timerExit.cancel();
                        }
                        intent.setClass( context, ManagerActivity.class );
                        startActivity( intent );
                    } else {
                        showNotAdiminDia();
                    }
                } else {
                    //设置管理模式
                    setisAdmin();
//                    intent.setClass(context, LoginActivity.class);
//                    startActivity(intent);
                    SoundPoolUtils.play( context, R.raw.raw_face, 0 );
                    intent.setClass( context, RegisterAndRecognizeActivity.class );
                    startActivity( intent );
                }
                break;
            case R.id.tv_exit:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                mRelaExit.setVisibility( View.GONE );
                exitLogin();
                showExitDia();
                break;
            case R.id.rela_search_pro:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                intent = new Intent( context, NewProDtaActivity.class );
                startActivity( intent );
                break;

            case R.id.tv_mac_rigth:

                LogUtil.e( TAG, NetStatusUtils.isConnected( context ) + "" );
                exitAfterMany();
                break;
        }
    }

    @Override
    public void getWeather(ResponseBean responseBean) {
        WeatherEntity weatherEntity = (WeatherEntity) responseBean.pullData();
        if (weatherEntity == null)
            return;
        if ("1".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_qing );
        } else if ("2".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_duoyun );
        } else if ("3".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_yin );
        } else if ("4".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_xiayu );
        } else if ("5".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_xue );
        } else if ("6".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_wu );
        } else if ("7".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_scb );
        } else if ("8".equals( weatherEntity.getType() )) {
            mImgWeather.setImageResource( R.mipmap.icon_weather_mai );
        } else {
            mImgWeather.setImageResource( R.mipmap.icon_weather_duoyun );
        }

        mTvDate.setText( weatherEntity.getDate() + "  " + weatherEntity.getWeek() );
        mTvInfo.setText( weatherEntity.getCity() + "  " + weatherEntity.getWeather() );
        mTvWendu.setText( weatherEntity.getTemperature() );


    }

    @Override
    public void getIndexCount(ResponseBean responseBean) {

        HwInfo hwInfo = (HwInfo) responseBean.pullData();
        mTvSearchAll.setText( Html.fromHtml( "总库存共 " + "<font color=\"#FFB000\">" + hwInfo.getAllHwInHospitalStock() + "</font>" + " 件耗材，点击查询..." ) );
//        SharedPreferencesUtils.put(context, Share_StockNum, hwInfo.getLocalHwStock());
    }

    @Override
    public void OnGetVersionInfoSuccess(ResponseBean responseBean) {
        ApkVersionEntity versionEntity = (ApkVersionEntity) responseBean.pullData();
        if (versionEntity == null)
            return;
        int version_code = versionEntity.getVersion_code();
        int localVersion = MacUtils.getLocalVersion( context );
        if (localVersion < version_code) {
            showToast( (versionEntity.isForcible() ? "true" : "false") + version_code + "" );
            NLogUtil.i( NLogUtil.INFO_App_Need_UPDATE, "localVersion:" + localVersion + "--newVersion:" + version_code );
            if (versionEntity.isForcible()) {
                showToast( "开始静默更新" );
                downloadApk( versionEntity.getVersion_url() );

            } else
                getVersion( versionEntity.getVersion_url(), versionEntity.getMessage(), versionEntity.getVersion_code(), versionEntity.isForcible() );
        }
    }

    @Override
    public void OnSendHwHeartSuccess(ResponseBean responseBean) {

    }

    @Override
    public void verifyIcCardSuccess(ResponseBean responseBean) {
        if (timerExit != null) {
            timerExit.cancel();
        }
        UserInfoEntity userInfoEntity = (UserInfoEntity) responseBean.pullData();
        MyApplication.application.setUserInfoEntity( userInfoEntity );
        loginSuccess();
        connect();

//        goTakeStock(context);
    }

    @Override
    public void onError(String msg) {
        ToastUtils.showText( msg );
    }

    /**
     * @author yu
     * @time 2020/6/28  10:25 AM
     * @decs：版本更新
     */
    private void getVersion(String url, String updateInfo, int code, boolean force) {
        AppUpdate appUpdate = new AppUpdate.Builder()
                //更新地址（必传）
                .newVersionUrl( url )
                // 版本号（非必填）
                .newVersionCode( String.valueOf( code ) )
                // 通过传入资源id来自定义更新对话框，注意取消更新的id要定义为btnUpdateLater，立即更新的id要定义为btnUpdateNow（非必填）
                .updateResourceId( R.layout.dialog_update )
                // 更新的标题，弹框的标题（非必填，默认为应用更新）
                .updateTitle( R.string.update_title )
                // 更新内容的提示语，内容的标题（非必填，默认为更新内容）
                .updateContentTitle( R.string.update_content_lb )
                // 更新内容（非必填，默认“1.用户体验优化\n2.部分问题修复”）
                .updateInfo( updateInfo )
                // 文件大小（非必填）
                // 保存文件路径（默认前缀：Android/data/包名/files/ 文件名：download）
//                .savePath("/A/B")
                //是否采取静默下载模式（非必填，只显示更新提示，后台下载完自动弹出安装界面），否则，显示下载进度，显示下载失败
                .isSilentMode( false )
                //是否强制更新（非必填，默认不采取强制更新，否则，不更新无法使用）
                .forceUpdate( force ? 1 : 0 )
                .build();
        new UpdateManager().startUpdate( MainActivity.this, appUpdate );
    }

    private void showNotAdiminDia() {
        commonShowDialog = new CommonShowDialog( context );
        commonShowDialog.setContent( "您没有管理权限 ，请联系管理员！" );
        commonShowDialog.setImgShow( R.mipmap.icon_exit_warn );
        commonShowDialog.show();
        countDownShowDia();
    }

    /**
     * 倒计时显示Dialog
     */
    private void countDownShowDia() {
        timerDialog = new CountDownTimer( 2000, 1000 ) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                commonShowDialog.dismiss();
                timerDialog.cancel();
            }
        }.start();
    }


    /**
     * 倒计时显示退出
     */
    @SuppressLint("SetTextI18n")
    private void countDownExit() {
        mRelaExit.setVisibility( View.VISIBLE );
        mTvName.setText( "Hi，" + MyApplication.getUserInfoGlob().getUsername() );
        timerExit = new CountDownTimer( 10000, 1000 ) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTvExit.setText( "安全退出  " + millisUntilFinished / 1000 + "s" );
            }

            @Override
            public void onFinish() {
                mRelaExit.setVisibility( View.GONE );
                exitLogin();
                showExitDia();

            }
        }.start();
    }

    private void connect() {
        //开灯
        readerBase.writeGpioValue( m_curReaderSetting.btReadId, (byte) 0x04, (byte) 0x01 );
        //开门
        new Handler().postDelayed( new Runnable() {
            @Override
            public void run() {
                readerBase.writeGpioValue( m_curReaderSetting.btReadId, (byte) 0x03, (byte) 0x01 );
                goTakeStock( context );
            }
        }, 100 );
    }


    /**
     * 连续点击多次退出
     */
    private void exitAfterMany() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy( mHits, 1, mHits, 0, mHits.length - 1 );
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//System.currentTimeMillis()

        if ((mHits[mHits.length - 1] - mHits[0] <= DURATION)) {
            String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！";
            Toast.makeText( MainActivity.this, tips, Toast.LENGTH_SHORT ).show();
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
            finish();
        }
        if ((mHits[mHits.length - 1] - mHits[2] <= DURATION)) {
            String tips = "您已在[" + DURATION + "]！！！" + MacUtils.getLocalVersion( context );
            Toast.makeText( MainActivity.this, tips, Toast.LENGTH_SHORT ).show();
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
//            finish();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            toolScanner.analysisKeyEvent( event );
            return true;
        }
        return super.dispatchKeyEvent( event );

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        exitLogin();
        LogUtil.e( TAG, "退出程序!!!!!!" );
        System.exit( 0 );
//        if (mSerialPort != null) {
//            mSerialPort.close();
//        }
//        if (timerExit != null) {
//            timerExit.cancel();
//        }
//        if (timerDialog != null) {
//            timerDialog.cancel();
//        }
//
//        if (DBUtils.getInstance() != null) {
//            DBUtils.getInstance().release();
//        }
//        //释放读写器上电掉电控制设备
//        ModuleManager.newInstance().setUHFStatus( false );
//        Beeper.release();


        super.onDestroy();
    }


    @Override
    public void onScanSuccess(String barcode) {
        if (barcode == null || TextUtils.isEmpty( barcode ))
            return;
        String s = UserCardUtil.decimal2Hex( barcode );
        String s1 = UserCardUtil.reverseCardId( s );
        LogUtil.e( "卡号：", barcode + " 转换后===" + s + "翻转===" + s1 );
//        //验证成功
//        readCardPresenter.verifyIcCard(s1);
        new Thread( new Runnable() {
            @Override
            public void run() {
                UserInfoEntity userEntity = DBUtils.getInstance().getUserByIdCardNo( s1 );
                if (userEntity != null) {
                    NLogUtil.i( NLogUtil.INFO_Scan_Card, "刷卡成功" + "[[User]]" + userEntity.toString() );
                    //成功
                    runOnUiThread( new Runnable() {
                        @Override
                        public void run() {
                            if (timerExit != null) {
                                timerExit.cancel();
                            }
                            MyApplication.application.setUserInfoEntity( userEntity );
                            loginSuccess();
                            connect();
                        }
                    } );
                } else {
                    NLogUtil.i( NLogUtil.INFO_Scan_Card, "刷卡失败，未配置卡片 barCode:" + barcode );
                    runOnUiThread( new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showText( "没有配置卡片" );
                        }
                    } );
                }
            }
        } ).start();


    }

    private void goTakeStock(Context context) {
        Intent intents = new Intent( context, TakeStockDtaActivity.class );
        startActivity( intents );
    }

    //event 没有管理权限
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddClientEvent(Event event) {
        if (event.getCode() == EventCode.EventNOTADMIN) {
            showNotAdiminDia();
        } else if (event.getCode() == EventCode.EventRefreshNum) {
            homePresenter.getIndexCount( macAddress );
        }
    }

    @NetworkSubscribe(netFilterType = NetFilterType.ALL)
    public void netWorkChangeCallBack(NetType netType) {
        switch (netType) {
            case MOBILE:
                Log.e( "MainActivity", "MainActivity 已连接移动网络" );
                break;
            case NONE:
                Log.e( "MainActivity", "MainActivity 网络断开" );
                break;
            case WIFI:
                Log.e( "MainActivity", "MainActivity 已连接到wifi" );
                break;
            default:
                break;
        }
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

        if (!checkPermissions( NEEDED_PERMISSIONS )) {
            ActivityCompat.requestPermissions( this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS );
        }

    }

    @Override
    public void onGlobalLayout() {
        mTvDate.getViewTreeObserver().removeOnGlobalLayoutListener( this );
        if (!checkPermissions( NEEDED_PERMISSIONS )) {
            ActivityCompat.requestPermissions( this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS );
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
//            return true;
//        }
        return super.onKeyDown( keyCode, event );
    }

    public void UsbManager() {
        wenkHandler = new MyHandler( MainActivity.this );
        MyApplication.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService( Context.USB_SERVICE ), this,
                ACTION_USB_PERMISSION );//初始化驱动入口
        if (!isOpen) {
            retval = MyApplication.driver.ResumeUsbList();
            if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
            {
//                Toast.makeText( MainActivity.this, "打开设备失败!",
//                        Toast.LENGTH_SHORT ).show();
                MyApplication.driver.CloseDevice();
            } else if (retval == 0) {
                if (!MyApplication.driver.UartInit()) {//对串口设备进行初始化操作
//                    Toast.makeText( MainActivity.this, "设备初始化失败!",
//                            Toast.LENGTH_SHORT ).show();
//                    Toast.makeText( MainActivity.this, "打开" +
//                                    "设备失败!",
//                            Toast.LENGTH_SHORT ).show();
                    return;
                }
                isOpen = true;
                new ReadThread().start();//开启读线程读取串口接收的数据
                //配置串口波特率，函数说明可参照编程手册
                if (MyApplication.driver.SetConfig( 9600, Byte.parseByte( "8" ), Byte.parseByte( "1" ), Byte.parseByte( "0" ), Byte.parseByte( "0" ) )
                ) {
                } else {
//                    Toast.makeText( MainActivity.this, "串口设置失败!",
//                            Toast.LENGTH_SHORT ).show();
                }
            }
        }


    }


    private class ReadThread extends Thread {
        @Override
        public void run() {

            byte[] buffer = new byte[4096];

            while (true) {

                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = MyApplication.driver.ReadData( buffer, 4096 );
                if (length > 0) {
//                    String recv = HexDump.toHexString(buffer);
                    String recv = new String( buffer, 0, length );
                    msg.obj = recv;
                    wenkHandler.sendMessage( msg );
                }
            }
        }
    }

    private static class MyHandler extends Handler {
        WeakReference<MainActivity> mainActivityWeakReference;

        MyHandler(MainActivity activity) {
            mainActivityWeakReference = new WeakReference<MainActivity>( activity );
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage( msg );
            MainActivity activity = mainActivityWeakReference.get();
            if (activity != null) {

//                T: 28.89, RH: 0.23
                String wenshiInfo = msg.obj.toString();
                LogUtil.e( "温控==", msg.obj.toString() );
                if (wenshiInfo.startsWith( "T" )) {
                    String[] split = wenshiInfo.split( "," );
                    if (split.length == 2) {
                        String wendu = split[0].replace( "T:", "" );
                        String shidu = split[1].replace( "RH:", "" );
                        LogUtil.e( "====", "wendu==" + wendu + "===" + "shidu===" + shidu );

                        activity.relaShidu.setVisibility( View.VISIBLE );
                        activity.relaWendu.setVisibility( View.VISIBLE );

                        activity.mTvWdu.setText( String.format( "%.1f", Double.parseDouble( wendu ) ) );
                        activity.mTvSdu.setText( String.valueOf( (int) (Double.parseDouble( shidu ) * 100) ) );
                    }
                }
            }
        }
    }

    public void downloadApk(String url) {
        Aria.download( this ).removeAllTask( true );
        //开启下载
//                .load("http://218.24.35.107/file/specialCabinet/signed_app-debug(1).apk")     //读取下载地址
        String filePath = Environment.getExternalStorageDirectory().getPath() + ConstantUrl.FILE_APK;
        File file = new File( filePath );
        if (file.exists()) {
            file.delete();
        }
        Aria.download( this )
                .load( url )     //读取下载地址
                .setFilePath( filePath, true ) //设置文件保存的完整路径
                .create();   //启动下载
    }

    /*
     * 任务完成
     */
    @Download.onTaskComplete
    protected void taskComplete(DownloadTask task) {
        showToast( "下载完成" );
        LogUtil.e( "yyd", "下载完成！" );
        LogUtil.e( "YYD", "是否有权限：" + isRoot() );
        install( Environment.getExternalStorageDirectory().getPath() + ConstantUrl.FILE_APK );
    }

    @Download.onTaskRunning
    public void running(DownloadTask task) {
        LogUtil.e( "yyd", "下载:" + task.getConvertCurrentProgress() );

    }
    @Download.onTaskFail
    public void  taskFail(DownloadTask task) {
    }
    public boolean install(String apkPath) {// apkPath:apk的存储路径
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec( "su" );
            dataOutputStream = new DataOutputStream( process.getOutputStream() );
            // 执行pm install命令
            LogUtil.e( "YYD", "要安装的apk路径:" + apkPath );
            String command = "pm install -t -r " + apkPath + "\n";// -t:允许apk被安装  -r :重新安装应用，且保留应用数据
            dataOutputStream.write( command.getBytes( Charset.forName( "utf-8" ) ) );
            dataOutputStream.flush();
            dataOutputStream.writeBytes( "exit\n" );
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader( new InputStreamReader( process.getErrorStream() ) );
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            LogUtil.e( "YYD", "install msg is " + msg );
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.contains( "Failure" )) {
                result = true;
            }

        } catch (Exception e) {
            //ToastUtil.showLongToast(KursaalApp.context,"设备未Root,请先Root后再继续使用!");
            LogUtil.e( e.getMessage(), e + "" );
            result = false;
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
                LogUtil.e( "YYD", "install: " + e.toString() );
            }
        }
        return result;
    }


    /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true，否则返回false。
     */
    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File( "/system/bin/su" ).exists() || new File( "/system/xbin/su" ).exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

}